import * as api from '@/services/vpnRoute';
import * as utils from '@/utils/utils';
import {
  AreaChartOutlined,
  ArrowDownOutlined,
  ArrowUpOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  PlusOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Badge, Button, Popconfirm, Select, Space, Tag } from 'antd';
import Countdown from 'antd/lib/statistic/Countdown';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import VpnRouteForm from './VpnRouteForm';
import * as c from '@/services/consts';
import GrafanaForm from '../VpnServerMonitor/components/GrafanaForm';

const VpnGroupTreeList: React.FC = () => {
  const [countdownTicks, setCountdownTicks] = useState<number>(
    Date.now() + 30000,
  );
  const [customCountdownTicks, setCustomCountdownTicks] =
    useState<number>(30000);
  const [countdownVisible, setCountdownVisible] = useState<string>('visible');

  // const [monitorData, setMonitorData] = useState<API.VpnRouteModel[]>(
  //   [],
  // );
  // const [controlState, setControlState] = useState<number>(0);
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.VpnRouteModel | undefined>(
    undefined,
  );
  
  const [formGrafanaVisible, setFormGrafanaVisible] = useState<boolean>(false);
  const [currentNode, setCurrentNode] = useState<API.VpnRouteModel | undefined>(undefined);
  const [currentUrlGrafana, setCurrentUrlGrafana] = useState<string | undefined>(undefined);

  
  const alertGreen = 104857600; //100*1024*1024
  const alertOrange = 209715200; //200*1024*1024

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const { hasRight } = useModel('useAuthModel');

  
  const {
    globalGrafanaModel,
  } = useModel('useGlobalModel', (model) => ({
    globalGrafanaModel: model.globalGrafanaModel,
  }));

  const reload = () => {
    // setControlState(new Date().getTime());
    actionRef.current?.reload();
    setCountdownTicks(Date.now() + customCountdownTicks);
  };

  const handleFormSubmit = async (record: API.VpnRouteModel) => {
    let result: API.Result;
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();
    }
  };

  const handleRemove = async (id: string) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  // const loadDataDo = async () =>
  // {
  //   if(hasRight("vpnserverMonitor_route")){
  //     const result = await api.list();

  //     if (result && result.success) {
  //       setMonitorData(result.data);
  //     } else {
  //       setMonitorData([]);
  //     }
  //   }
  // };

  // useEffect(() => {
  //   loadDataDo();
  // }, [controlState]);

  let columns: ProColumns<API.VpnRouteModel>[] = [
    // {
    //   title: '状态',
    //   align: 'center',
    //   width: 60,
    //   dataIndex: 'status',
    //   sorter: true,
    //   search: false,
    //   valueEnum: {
    //     true: { status: 'Success' },
    //     false: { status: 'Error' },
    //   },
    // },
    {
      title: '类型',
      width: 80,
      dataIndex: 'type',
      sorter: (a, b) => a.type - b.type,
      render: (_, record) =>{
        return c.getObjectText(c.RouteTypes, record.type)
      }
    },
    {
      title: '名称',
      // width: 250,
      dataIndex: 'name',
      sorter: (a, b) => (a.name ?? '').localeCompare(b.name ?? ''),
    },
    {
      title: 'IP',
      // width: 250,
      dataIndex: 'ip',
      sorter: (a, b) => (a.ip ?? '').localeCompare(b.ip ?? ''),
    },
    {
      title: '在线',
      dataIndex: 'appStartTime',
      width: 60,
      sorter: (a, b) => (a.appStartTime ?? 0) - (b.appStartTime ?? 0),
      render: (_, record) => {
        return record.appStartTime ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    {
      title: '版本号',
      dataIndex: 'appVer',
      width: 80,
      sorter: (a, b) => (a.appVer ?? 0) - (b.appVer ?? 0),
    },
    {
      title: '运行时间',
      dataIndex: 'appStartTime',
      width: 120,
      sorter: (a, b) => (a.appStartTime ?? 0) - (b.appStartTime ?? 0),
      render: (_, record) => {
        return record.appStartTime && record.appStartTime > 0
          ? utils.formatDuration(record.appStartTime)
          : '';
      },
    },
    {
      title: '1分钟调度次数',
      dataIndex: 'qps1Min',
      width: 150,
      sorter: (a, b) => (a.qps1Min ?? 0) - (b.qps1Min ?? 0),
      render: (_, record) => {
        return utils.formatNumber(record.qps1Min);
      },
    },
    {
      title: '24小时调度次数',
      dataIndex: 'qps24Hour',
      width: 150,
      sorter: (a, b) => (a.qps24Hour ?? 0) - (b.qps24Hour ?? 0),
      render: (_, record) => {
        return record.qps24Hour && record.qps24Hour < 0
          ? '-'
          : utils.formatNumber(record.qps24Hour);
      },
    },
    {
      title: '总调度次数',
      dataIndex: 'routeTotal',
      width: 150,
      sorter: (a, b) => (a.routeTotal ?? 0) - (b.routeTotal ?? 0),
      render: (_, record) => {
        return utils.formatNumber(record.routeTotal);
      },
    },
    {
      title: '1分钟授权次数',
      dataIndex: 'authQps',
      width: 150,
      sorter: (a, b) => (a.authQps ?? 0) - (b.authQps ?? 0),
      render: (_, record) => {
        return utils.formatNumber(record.authQps);
      },
    },
    {
      title: '总授权次数',
      dataIndex: 'authTotal',
      width: 150,
      sorter: (a, b) => (a.authTotal ?? 0) - (b.authTotal ?? 0),
      render: (_, record) => {
        return utils.formatNumber(record.authTotal);
      },
    },
    {
      title: '下载',
      // align: 'center',
      dataIndex: 'download',
      sorter: (a, b) => (a.download ?? 0) - (b.download ?? 0),
      width: 100,
      render: (_, record) => {
        return (
          <Tag
            color={
              record.download
                ? record.download <= alertGreen
                  ? 'green'
                  : record.download <= alertOrange
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              <ArrowDownOutlined /> {utils.formatRate(record.download, true)}
            </b>
          </Tag>
        );
      },
    },
    {
      title: '上传',
      // align: 'center',
      dataIndex: 'upload',
      sorter: (a, b) => (a.upload ?? 0) - (b.upload ?? 0),
      width: 120,
      render: (_, record) => {
        return (
          <span>
            <Tag
              color={
                record.upload
                  ? record.upload <= alertGreen
                    ? 'green'
                    : record.upload <= alertOrange
                    ? 'orange'
                    : 'red'
                  : ''
              }
            >
              <b>
                <ArrowUpOutlined /> {utils.formatRate(record.upload, true)}
              </b>
            </Tag>
            
            <a
              onClick={(e) => {
                setFormGrafanaVisible(true);
                setCurrentNode(record);
                setCurrentUrlGrafana(globalGrafanaModel?.urlGrafanaNode);
              }}
            >
              <AreaChartOutlined />
            </a>
          </span>
        );
      },
    },
    {
      title: 'CPU',
      // align: 'center',
      dataIndex: 'cpuUsed',
      width: 100,
      sorter: (a, b) => (a.cpuUsed ?? 0) - (b.cpuUsed ?? 0),
      render: (_, record) => {
        return (
          <Tag
            color={
              record.cpuUsed
                ? record.cpuUsed < 0.5
                  ? 'green'
                  : record.cpuUsed < 0.9
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              {record.cpuCore} / {utils.formatPercentage(record.cpuUsed, 1)}%
            </b>
          </Tag>
        );
      },
    },
    {
      title: '内存',
      dataIndex: 'memUsedPer',
      // align: 'center',
      width: 120,
      sorter: (a, b) => (a.memUsedPer ?? 0) - (b.memUsedPer ?? 0),
      render: (_, record) => {
        let usedPer = record.memUsedPer ?? 0;
        return (
          <Tag
            color={
              usedPer != 0
                ? usedPer < 0.5
                  ? 'green'
                  : usedPer < 0.9
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              {utils.formatRate(record.memTotal, true)} /{' '}
              {utils.formatPercentage(usedPer, 1)}%
            </b>
          </Tag>
        );
      },
    },
    {
      title: '排序',
      align: 'center',
      width: 80,
      dataIndex: 'sort',
      sorter: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 100,
      render: (_, record) => {
        let cmps = [];

        if (hasRight('vpnroute_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('vpnroute_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable<API.VpnRouteModel>
        rowKey="instId"
        actionRef={actionRef}
        formRef={formRef}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        toolbar={{
          filter: (
            <>
              <Space
                style={{
                  marginRight: '0px',
                }}
              >
                <span>
                  <Countdown
                    title=""
                    key="cdRefresh"
                    value={countdownTicks}
                    format="s"
                    prefix=""
                    suffix="秒后刷新"
                    valueStyle={{
                      fontSize: 14,
                      color: 'gray',
                    }}
                    style={{ visibility: countdownVisible }}
                    onFinish={reload}
                  />
                </span>
                <span>
                  <Select
                    defaultValue={30}
                    style={{ width: 80 }}
                    options={[
                      {
                        label: '禁止',
                        value: 0,
                      },
                      {
                        label: '15秒',
                        value: 15,
                      },
                      {
                        label: '20秒',
                        value: 20,
                      },
                      {
                        label: '30秒',
                        value: 30,
                      },
                      {
                        label: '60秒',
                        value: 60,
                      },
                      {
                        label: '120秒',
                        value: 120,
                      },
                    ]}
                    onChange={(val) => {
                      if (val == 0) {
                        setCountdownVisible('hidden');
                        setCountdownTicks(-1);
                      } else {
                        if (countdownVisible == 'hidden') {
                          setCountdownVisible('visible');
                          setCountdownTicks(Date.now() + val * 1000);
                          actionRef.current?.reload();
                        } else {
                          setCustomCountdownTicks(val * 1000);
                          setCountdownTicks(Date.now() + val * 1000);
                          actionRef.current?.reload();
                        }
                      }
                    }}
                  />
                </span>
              </Space>
            </>
          ),
        }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];
          if (hasRight('vpnroute_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                  setCurrent(undefined);
                }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ]);
          }
          return toolbarDoms;
        }}
        columns={columns}
        // dataSource={monitorData}
        request={api.list}
      />
      <VpnRouteForm
        visible={formVisible}
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
      <GrafanaForm
        visible={formGrafanaVisible}
        group={undefined}
        server={currentNode}
        urlGrafana={currentUrlGrafana}
        groups={undefined}
        grafanaTitle={undefined}
        onCancel={() => {
          setFormGrafanaVisible(false);
          setCurrentNode(undefined);
          setCurrentUrlGrafana(undefined);
        }}
      />
    </PageContainer>
  );
};

export default VpnGroupTreeList;
